#!/usr/bin/env python
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""Simple app to demonstrate OAuth verification support.

Exposes one handler that responds to 3-legged OAuth requests.

See http://code.google.com/intl/en/appengine/docs/python/oauth/
"""
from google.appengine.dist import use_library
use_library('django', '1.1')

import logging
import sys
from google.appengine.api import oauth
from google.appengine.ext import webapp
import wsgiref.handlers
from django.utils import simplejson

    
class OAuth3LeggedHandler(webapp.RequestHandler):
  """Handler for 3-legged OAuth requests."""
  
  def _verifyRequest(self):
    """Verify a request and return JSON with data about the user."""
    output = {}
    try:
      user = oauth.get_current_user()
      output['status'] = 'ok'
      output['nickname'] = user.nickname()
      output['email'] = user.email()
      output['user_id'] = user.user_id()
      output['is_admin'] = oauth.is_current_user_admin()
      arguments = {}
      for arg in self.request.arguments():
        arguments[arg] = self.request.get_all(arg)
      output['arguments']= arguments
      self.response.set_status(200)
    except oauth.InvalidOAuthTokenError, e:
      self.response.set_status(401)
      output['status'] = 'InvalidOAuthTokenError: %s' % e
    except oauth.InvalidOAuthParametersError, e:
      self.response.set_status(400)
      output['status'] = 'InvalidOAuthParametersError: %s' % e
    except oauth.InvalidOAuthRequestError, e:
      self.response.set_status(400)
      output['status'] = 'OAuthRequestError: %s' % e
    except oauth.OAuthServiceFailureError, e:
      self.response.set_status(500)
      output['status'] = 'OAuthServiceFailureError: %s' % e
    except Exception, e:
      self.response.set_status(500)
      output['status'] = 'Exception: %s' % e
    self.response.headers['content-type'] = 'application/json'
    self.response.out.write(simplejson.dumps(output, indent=2))
    
  def get(self):
    """Handle GET events."""
    self._verifyRequest()
    
  def post(self):
    """Handle POST events."""
    self._verifyRequest()
      

# Map URLs to our RequestHandler class above
_URLS = [
    ('/whoami', OAuth3LeggedHandler),
]


def main(argv):
  application = webapp.WSGIApplication(_URLS, debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main(sys.argv)
